package cn.sc.summer.rabbitmq.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import cn.sc.summer.constant.gateway.GatewayConstant;
import cn.sc.summer.constant.gateway.GatewayInstance;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.rabbitmq.builder.RabbitBuilder;
import cn.sc.summer.rabbitmq.builder.RabbitMessageBuilderDirector;
import cn.sc.summer.rabbitmq.service.RabbitService;
import cn.sc.summer.redis.util.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 类名：mq基础服务
 *
 * @author a-xin
 * @date 2024/8/3 00:55
 */
@Slf4j
@Service
public class RabbitServiceImpl implements RabbitService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 服务刷新网关接口
     *
     * @param serverName 服务名称
     * @param serverHost 服务ip:port
     */
    @Override
    public void registerServer(String serverName, String serverHost) {
        JSONObject message = new RabbitMessageBuilderDirector(new RabbitBuilder()).build();
        GatewayInstance gatewayInstance = new GatewayInstance();
        gatewayInstance.setServerName(serverName);
        gatewayInstance.setServerHost(serverHost);
        String serverKey = RandomUtil.randomString(16);
        RedisHelper.set(GatewayConstant.SERVER_INSTANCE_KEY + ":" + serverKey, serverKey, 10, TimeUnit.SECONDS);
        gatewayInstance.setServerKey(serverKey);
        message.put(RabbitConstant.MESSAGE_KEY, JSONObject.toJSONString(gatewayInstance));
        rabbitTemplate.convertAndSend(
                RabbitConstant.GATEWAY_INSTANCE_EXCHANGE,
                RabbitConstant.GATEWAY_INSTANCE_ROUTING_KEY,
                message.toJSONString());
    }

}
